#include "Http.hpp"
#include "Common.hpp"
#include "StudentsManager.hpp"
#include <algorithm>
#include <sstream>
#include <iomanip>

// 全局学生管理器实例
StudentsManager g_studentsManager;

void PrintAllStudents() {
    std::cout << "当前所有学生: ";
    for (const auto& s : g_studentsManager.GetAllStudents()) {
        std::cout << s._id << " ";
    }
    std::cout << std::endl;
}

// URL解码
std::string UrlDecode(const std::string& str) {
    std::string result;
    size_t length = str.length();

    for (size_t i = 0; i < length; ++i) {
        if (str[i] == '%' && i + 2 < length && std::isxdigit(str[i+1]) && std::isxdigit(str[i+2])) {
            // 解码 %XX
            int value = 0;
            std::istringstream iss(str.substr(i + 1, 2));
            iss >> std::hex >> value;
            result += static_cast<char>(value);
            i += 2;
        } else if (str[i] == '+') {
            // + 号也表示空格
            result += ' ';
        } else {
            result += str[i];
        }
    }
    return result;
}

// 解析URL参数
std::unordered_map<std::string, std::string> ParseParams(const std::string& params) {
    std::unordered_map<std::string, std::string> result;
    if (params.empty()) return result;

    std::istringstream ss(params);
    std::string pair;

    while (std::getline(ss, pair, '&')) {
        size_t pos = pair.find('=');
        if (pos != std::string::npos) {
            std::string key = pair.substr(0, pos);
            std::string value = pair.substr(pos + 1);

            // 完整URL解码
            result[key] = UrlDecode(value);
        }
    }
    return result;
}

// 生成学生表格HTML
std::string GenerateStudentTable(const std::vector<Student>& students) {
    std::ostringstream html;
    
    for (const auto& student : students) {
        int total = student.GetTotalScore();
        double average = student.GetAverageScore();
        std::string grade = student.GetGrade();
        
        html << "<tr>"
             << "<td>" << student._id << "</td>"
             << "<td>" << student._name << "</td>"
             << "<td>" << student._age << "</td>"
             << "<td>" << student._sex << "</td>"
             << "<td>" << student._chinese << "</td>"
             << "<td>" << student._math << "</td>"
             << "<td>" << total << "</td>"
             << "<td>" << std::fixed << std::setprecision(1) << average << "</td>"
             << "<td>" << grade << "</td>"
             << "<td class=\"action-buttons\">"
             << "<button class=\"btn btn-warning\" onclick=\"editStudent('"
             << student._id << "', '" << student._name << "', " << student._age 
             << ", '" << student._sex << "', " << student._chinese << ", " << student._math << ")\">编辑</button>"
             << "<button class=\"btn btn-danger\" onclick=\"deleteStudent('" << student._id << "')\">删除</button>"
             << "</td>"
             << "</tr>";
    }
    
    return html.str();
}

// 生成统计信息HTML
std::string GenerateStatsHTML() {
    std::ostringstream html;
    
    size_t count = g_studentsManager.GetStudentCount();
    double chineseAvg = g_studentsManager.GetChineseAverage();
    double mathAvg = g_studentsManager.GetMathAverage();
    double totalAvg = g_studentsManager.GetTotalAverage();
    double passRate = g_studentsManager.GetPassRate();
    double failRate = g_studentsManager.GetFailRate();
    
    StudentsManager::GradeStats gradeStats = g_studentsManager.GetGradeStats();
    
    html << "<div class=\"stat-card\">"
         << "<h3>学生总数</h3>"
         << "<div class=\"value\">" << count << "</div>"
         << "</div>";
         
    html << "<div class=\"stat-card\">"
         << "<h3>语文平均分</h3>"
         << "<div class=\"value\">" << std::fixed << std::setprecision(1) << chineseAvg << "</div>"
         << "</div>";
         
    html << "<div class=\"stat-card\">"
         << "<h3>数学平均分</h3>"
         << "<div class=\"value\">" << std::fixed << std::setprecision(1) << mathAvg << "</div>"
         << "</div>";
         
    html << "<div class=\"stat-card\">"
         << "<h3>总体平均分</h3>"
         << "<div class=\"value\">" << std::fixed << std::setprecision(1) << totalAvg << "</div>"
         << "</div>";
         
    html << "<div class=\"stat-card\">"
         << "<h3>及格率</h3>"
         << "<div class=\"value\">" << std::fixed << std::setprecision(1) << passRate << "%</div>"
         << "</div>";
         
    html << "<div class=\"stat-card\">"
         << "<h3>不及格率</h3>"
         << "<div class=\"value\">" << std::fixed << std::setprecision(1) << failRate << "%</div>"
         << "</div>";
         
    html << "<div class=\"stat-card\">"
         << "<h3>优秀率</h3>"
         << "<div class=\"value\">" << std::fixed << std::setprecision(1) << gradeStats.excellent << "%</div>"
         << "</div>";
         
    html << "<div class=\"stat-card\">"
         << "<h3>良好率</h3>"
         << "<div class=\"value\">" << std::fixed << std::setprecision(1) << gradeStats.good << "%</div>"
         << "</div>";
    
    return html.str();
}

// 生成完整的学生管理页面
std::string GenerateManageStudentsPage(const std::vector<Student>& students = std::vector<Student>()) {
    std::string tableContent;
    std::vector<Student> displayStudents;
    
    if (students.empty()) {
        displayStudents = g_studentsManager.GetAllStudents();
    } else {
        displayStudents = students;
    }
    
    tableContent = GenerateStudentTable(displayStudents);
    std::string statsContent = GenerateStatsHTML();
    
    // 读取HTML模板
    std::string htmlTemplate;
    if (!Util::ReadFile("./wwwroot/manage_students.html", &htmlTemplate)) {
        std::cout << "无法读取 manage_students.html 模板文件" << std::endl;
        return "<html><body><h1>页面加载失败</h1><p>无法找到页面模板文件</p></body></html>";
    }
    
    std::cout << "成功读取HTML模板，长度: " << htmlTemplate.length() << std::endl;
    
    // 替换统计信息占位符
    size_t statsPos = htmlTemplate.find("<!-- 统计卡片将通过JavaScript动态生成 -->");
    if (statsPos != std::string::npos) {
        htmlTemplate.replace(statsPos, 59, statsContent);
        std::cout << "成功替换统计信息内容" << std::endl;
    } else {
        std::cout << "警告：未找到统计信息占位符" << std::endl;
    }
    
    // 替换学生表格占位符
    size_t tablePos = htmlTemplate.find("<!-- 学生数据将通过JavaScript动态生成 -->");
    if (tablePos != std::string::npos) {
        htmlTemplate.replace(tablePos, 49, tableContent);
        std::cout << "成功替换学生表格内容" << std::endl;
    } else {
        std::cout << "警告：未找到学生表格占位符" << std::endl;
    }
    
    std::cout << "最终生成的页面长度: " << htmlTemplate.length() << std::endl;
    return htmlTemplate;
}

// 学生管理系统路由处理函数
void ManageStudentsHandler(HttpRequest& req, HttpResponse& resp) {
    g_studentsManager.LoadFromFile();

    std::cout << "处理学生管理请求，参数: " << req.Args() << std::endl;
    
    // 解析参数
    auto params = ParseParams(req.Args());
    std::string action = params["action"];
    
    std::string responseHtml;
    
    if (action.empty()) {
        // 显示学生列表页面
        responseHtml = GenerateManageStudentsPage();
    }
    else if (action == "add") {
        // 添加学生
        Student student;
        student._id = params["id"];
        student._name = params["name"];
        student._age = std::stoi(params["age"]);
        student._sex = params["sex"];
        student._chinese = std::stoi(params["chinese"]);
        student._math = std::stoi(params["math"]);
        
        if (g_studentsManager.AddStudent(student)) {
            std::cout << "成功添加学生: " << student._id << std::endl;
        } else {
            std::cout << "添加学生失败，学号已存在: " << student._id << std::endl;
        }

        PrintAllStudents();
        
        responseHtml = GenerateManageStudentsPage();
    }
    else if (action == "delete") {
        // 删除学生
        std::string id = params["id"];
        if (g_studentsManager.DeleteStudent(id)) {
            std::cout << "成功删除学生: " << id << std::endl;
        } else {
            std::cout << "删除学生失败: " << id << std::endl;
        }

        PrintAllStudents();
        
        responseHtml = GenerateManageStudentsPage();
    }
    else if (action == "update") {
        // 更新学生
        Student student;
        student._id = params["id"];
        student._name = params["name"];
        student._age = std::stoi(params["age"]);
        student._sex = params["sex"];
        student._chinese = std::stoi(params["chinese"]);
        student._math = std::stoi(params["math"]);
        
        if (g_studentsManager.UpdateStudent(student)) {
            std::cout << "成功更新学生: " << student._id << std::endl;
        } else {
            std::cout << "更新学生失败: " << student._id << std::endl;
        }

        PrintAllStudents();
        
        responseHtml = GenerateManageStudentsPage();
    }
    else if (action == "search") {
        // 搜索学生
        std::string id = params["id"];
        Student* student = g_studentsManager.FindStudent(id);
        
        std::vector<Student> searchResults;
        if (student != nullptr) {
            searchResults.push_back(*student);
            std::cout << "找到学生: " << id << std::endl;
        } else {
            std::cout << "未找到学生: " << id << std::endl;
        }

        PrintAllStudents();
        
        responseHtml = GenerateManageStudentsPage(searchResults);
    }
    else {
        // 未知操作
        responseHtml = GenerateManageStudentsPage();
    }
    
    // 设置响应
    resp.SetCode(200);
    resp.SetHeader("Content-Type", "text/html; charset=utf-8");
    resp.SetText(responseHtml);
}

int main(int argc, char* argv[])
{
    if(argc < 2)
    {
        std::cerr << "Usage: " << argv[0] << " port" << std::endl;
        exit((int)exit_code::USAGE_ERR);
    }

    // 初始化学生管理器，加载数据
    g_studentsManager.LoadFromFile();
    std::cout << "学生管理系统启动，已加载 " << g_studentsManager.GetStudentCount() << " 个学生数据" << std::endl;

    // 创建HTTP服务器
    std::unique_ptr<Http> http = std::make_unique<Http>(std::stoi(argv[1]));
    
    // 注册学生管理路由
    http->RegisterService("/manage_students", ManageStudentsHandler);
    
    // 启动服务器
    http->Start();
    return 0;
}